package server

import (
	"chat/global"
	"chat/internal/model"
	"chat/internal/service"
	"encoding/json"
	"fmt"
	"time"
)

var (
	MyServer = &Server{
		Clients:    make(map[int]*Client),
		Register:   make(chan *Client),
		UnRegister: make(chan *Client),
		Broadcast:  make(chan []byte),
	}
)

type Server struct {
	Clients    map[int]*Client
	Register   chan *Client
	UnRegister chan *Client
	Broadcast  chan []byte
}

func (s *Server) Run() {
	for {
		select {
		case client := <-s.Register:
			s.Clients[client.ID] = client
			msg := model.Message{
				Content: "welcome!",
			}
			protoMsg, _ := json.Marshal(msg)
			client.Send <- protoMsg
		case client := <-s.UnRegister:
			if _, ok := s.Clients[client.ID]; ok {
				close(client.Send)
				delete(s.Clients, client.ID)
			}
		case message := <-s.Broadcast:
			msg := &model.Message{}
			err := json.Unmarshal(message, msg)
			if err != nil {
				global.Logger.Infof("json.Unmarshal err : %v\n", err)
				continue
			}
			if msg.CreatedAt == 0 {
				msg.CreatedAt = time.Now().UnixMilli()
			}
			err = service.SaveMessage(msg)
			if err != nil {
				global.Logger.Infof("service.SaveMessage err : %v\n", err)
				continue
			}

			if msg.MessageType == 1 {
				fmt.Println(msg.FromUserId, ": ", msg.Content)
				// 用户不在线
				client, ok := s.Clients[msg.ToUserId]
				if ok {
					client.Send <- message
				}
			} else if msg.MessageType == 2 {
				// 查询群中所以好友的id
				ids, err := service.GetUsersByGroupId(msg.ToUserId)
				if err != nil {
					global.Logger.Infof("service.GetUsersByGroupId err: %+v", err)
					continue
				}
				// 给所有群友发送该消息
				for _, id := range ids {
					if id == msg.FromUserId {
						continue
					}
					client, ok := s.Clients[id]
					if ok {
						client.Send <- message
					}
				}

			}
		}
	}
}
